package com.esiag.isidis.marshaling;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class RawActionSender {
	private static RawActionSender instance = null;
	// private int port;//
	private String ip;
	private int port;

	// ghitah
	// IAdresseRef iar = new DataBaseAccess();

	public static RawActionSender getInstance() throws UnknownHostException {
		if (instance == null)
			instance = new RawActionSender();

		return instance;
	}

	private RawActionSender() throws UnknownHostException {
		XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(
				"UDP.xml"));
		IpPort adresse = factory.getBean("ipPort", IpPort.class);
		ip = adresse.getIp();
		port = adresse.getPort();
		System.out.println(ip + ">>" + port);

	}


	public void sendTramExample(byte[] tram) {
		try {
		
			try {
				byte[] papier = tram;
				
				InetAddress iad = InetAddress.getByName(ip);
		

				///////////////////////////////////////////////////////////////////////////////////////////////////
				/*
				 * TODO: BY GHITAH JABRI
				 */
				String binary = "";
				for (int i = 0; i < tram.length; i++) {
					binary += Integer.toBinaryString(tram[i]);
					System.out.println("binary:"
							+ Integer.toBinaryString(tram[i]));
				}
				papier = new String(binary).getBytes("UTF-8");
				///////////////////////////////////////////////////////////////////////////////////////////////////

				DatagramPacket lettre = new DatagramPacket(papier,
						papier.length, iad, port);
				DatagramSocket bal = new DatagramSocket();
				bal.send(lettre);

			} catch (Exception e) {
				System.out.println("afficher erreur " + e.getMessage());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
